const fs = require("fs")
const path = require("path")
const Sequelize = require("sequelize")
const Router = require("koa-router")
const schedule = require("node-schedule")
const config = require("./config")

// 读取目录
function load(dir, cb) {
  // 获取绝对路径
  const url = path.resolve(__dirname, dir)
  const files = fs.readdirSync(url)
  // 遍历
  files.forEach(filename => {
    // 去掉后缀
    filename = filename.replace(".js", "")
    // 导入文件
    const file = require(url + "/" + filename)
    cb(filename, file)
  })
}

function initRouter(app) {
  const router = new Router()

  load("routes", (filename, routes) => {
    // index前缀处理
    const prefix = filename === "index" ? "" : `/${filename}`

    // 路由类型判断
    routes = typeof routes === "function" ? routes(app) : routes

    // 遍历添加路由
    Object.keys(routes).forEach(key => {
      const [method, path] = key.split(" ")
      console.log(
        `正在映射地址 ${method.toLocaleUpperCase()} ${prefix}${
          path === "/" ? "" : path
        }`
      )
      // 注册
      // router[method](prefix + (path === "/" ? "" : path), routes[key])
      router[method](prefix + (path === "/" ? "" : path), async ctx => {
        // 将上下文挂载到app
        app.ctx = ctx
        //路由接收并处理app
        await routes[key](app)
      })
    })
  })
  return router
}

function initController(app) {
  const controllers = {}
  // 读取ctrl
  load("controller", (filename, controller) => {
    controllers[filename] = controller(app)
  })
  return controllers
}

function initServce() {
  const services = {}
  load("service", (filename, service) => {
    services[filename] = service
  })
  return services
}

function loadConfig(app) {
  load("config", (filename, conf) => {
    if (config.db) {
      app.$db = new Sequelize(conf.db)
      // 加载模型
      app.$model = {}
      load("model", (filename, { schema, options }) => {
        app.$model[filename] = app.$db.define(filename, schema, options)
      })
      app.$db.sync()
    }
    if (conf.middleware) {
      conf.middleware.forEach(el => {
        const midPath = path.resolve(__dirname, "middleware", el)
        app.$app.use(require(midPath))
      })
    }
  })
}

function initSchedule() {
  load("schedule", (filename, schduleConfig) => {
    schedule.scheduleJob(schduleConfig.interval, schduleConfig.handler)
  })
}

module.exports = {
  initRouter,
  initController,
  initServce,
  loadConfig,
  initSchedule
}
